package com.yy.micro.magic.ext.domain.code;

import com.fasterxml.jackson.annotation.JsonIgnore;

import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Objects;
import java.util.Optional;

public class CodeMap {
    private String name;

    private List<CodeMapItem> items;

    public String getName() {
        return name;
    }

    public void setName(final String name) {
        this.name = name;
    }

    public List<CodeMapItem> getItems() {
        return items;
    }

    public void setItems(final List<CodeMapItem> items) {
        this.items = items;
    }

    @JsonIgnore
    public boolean match(String name,Object value){
        return this.name.equals(name) && null != findTargetValue(value);
    }

    @JsonIgnore
    public Object findTargetValue(Object value){
        return findTargetValue(value,null);
    }
    @JsonIgnore
    public Object findTargetValue(Object value,Object defaultValue){
        if (!Objects.isNull(value) && !CollectionUtils.isEmpty(items)){
            Optional<CodeMapItem> item=items.stream().filter(i-> i.matchValue(value)).findFirst();
            if (item.isPresent()){
                return item.get().getTargetValue();
            }
        }
        return defaultValue;
    }
    @JsonIgnore
    public CodeMapItem findCodeItem(Object value){
        if (!Objects.isNull(value) && !CollectionUtils.isEmpty(items)){
            Optional<CodeMapItem> item=items.stream().filter(i-> i.matchValue(value)).findFirst();
            if (item.isPresent()){
                return item.get();
            }
        }
        return null;
    }

    @Override
    public boolean equals(final Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        final CodeMap codeMap = (CodeMap) o;
        return Objects.equals(name, codeMap.name) && Objects.equals(items, codeMap.items);
    }

    @Override
    public int hashCode() {
        return Objects.hash(name, items);
    }
}
